//
//  BKActionSheet.m
//  XPhoto
//
//  Created by baboy on 2019/5/31.
//  Copyright © 2019 baboy. All rights reserved.
//

#import "BKActionSheet.h"
#import "NSString+x.h"
#import "BKView.h"

#define BACKGROUND_COLOR [UIColor colorWithWhite:0.1 alpha:0.3]
#define BUTTON_TITLE_FONT [UIFont systemFontOfSize:14]
#define SUB_TITLE_FONT [UIFont systemFontOfSize:12]
#define SEP_LINE_COLOR  [UIColor colorWithWhite:0.88 alpha:1]
#define BG_COLOR [UIColor colorWithWhite:0.9 alpha:1]


#define BUTTON_TITLE_COLOR [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1]
#define SUB_TITLE_COLOR  [UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:1]

@interface BKActionSheet()
@property(nonatomic, strong) NSString *title;
@property(nonatomic, strong) NSMutableArray *titles;
@property(nonatomic, strong) NSString *cancelButtonTitle;
@property(nonatomic, strong) NSString *destructiveButtonTitle;
@property(nonatomic, strong) NSMutableArray *buttons;

@property(nonatomic, assign) id<BKActionSheetDelegate> delegate;
@end
@implementation BKActionSheet

- (id) initWithTitle:(NSString * _Nullable)title
               items:(NSArray *)items
            delegate:(id<BKActionSheetDelegate>)delegate
   cancelButtonTitle:(NSString *)cancelButtonTitle
destructiveButtonTitle:(NSString *_Nullable)destructiveButtonTitle{
    if(self = [super initWithFrame:[APP_KEY_WIN screen].bounds]){
        self.title = title;
        self.cancelButtonTitle = cancelButtonTitle;
        self.destructiveButtonTitle = destructiveButtonTitle;
        NSMutableArray *titles = [NSMutableArray array];
        
        int index = 0;
        if (items) {
            [titles addObjectsFromArray:items];
        }
        if(destructiveButtonTitle){
            [titles addObject:@{
                                @"title": destructiveButtonTitle,
                                @"color": [UIColor redColor],
                                @"index": [NSNumber numberWithInt:index]
             }];
        }
        self.titles = titles;
        self.delegate = delegate;
        [self setupViews];
    }
    return self;
}

- (id) initWithItems:(NSArray*)titles
             delegate:(nullable id<BKActionSheetDelegate>) delegate
    cancelButtonTitle:(nullable NSString *)cancelButtonTitle{
    
    if(self = [super initWithFrame:[APP_KEY_WIN screen].bounds]){
        self.titles = [NSMutableArray arrayWithArray:titles];
        self.cancelButtonTitle = cancelButtonTitle;
        self.delegate = delegate;
        [self setupViews];
    }
    return self;
}
- (UIButton *)createItemButton:(NSDictionary *)item withFrame:(CGRect) itemFrame{
    CGFloat verPadding = 15;
    
    NSString *title = [item objectForKey:@"title"];
    CGSize titleSize = [title  sizeWithAttributes:@{NSFontAttributeName: BUTTON_TITLE_FONT}];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, verPadding, itemFrame.size.width, titleSize.height+2)];
    titleLabel.font = BUTTON_TITLE_FONT;
    titleLabel.textColor = BUTTON_TITLE_COLOR;
    titleLabel.text = title;
    titleLabel.textAlignment = NSTextAlignmentCenter;
    
    itemFrame.size.height = titleSize.height+2*verPadding;
    
    NSString *subtitle = [item objectForKey:@"subtitle"];
    CGSize subtitleSize = CGSizeZero;
    UILabel *subtitleLabel = nil;
    if (subtitle) {
        subtitleSize = [title  sizeWithAttributes:@{NSFontAttributeName: SUB_TITLE_FONT}];
        subtitleLabel = [[UILabel alloc]  initWithFrame:CGRectMake(0, titleLabel.frame.origin.y+titleLabel.frame.size.height+2, self.bounds.size.width, subtitleSize.height)];
        subtitleLabel.font = SUB_TITLE_FONT;
        subtitleLabel.textColor = SUB_TITLE_COLOR;
        subtitleLabel.text = subtitle;
        subtitleLabel.textAlignment = NSTextAlignmentCenter;
        itemFrame.size.height += subtitleSize.height+2;
    }
    
    
    UIButton *itemView = [UIButton buttonWithType:UIButtonTypeCustom];
    itemView.frame = itemFrame;
    itemView.layer.borderColor = SEP_LINE_COLOR.CGColor;
    itemView.layer.borderWidth = 1;
    itemView.backgroundColor = [UIColor whiteColor];
    [itemView addSubview:titleLabel];
    if (subtitleLabel) {
        [itemView addSubview:subtitleLabel];
    }
    return itemView;
}
- (void)setupViews{
    self.backgroundView = [[UIView alloc] initWithFrame:self.bounds];
    self.backgroundView.backgroundColor = BACKGROUND_COLOR;
    UITapGestureRecognizer *closeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(close:)];
    [self.backgroundView addGestureRecognizer:closeTap];
    [self addSubview:self.backgroundView];
    
    self.buttons = [NSMutableArray array];
    
    self.contentView = [[UIView alloc] initWithFrame:self.bounds];
    self.contentView.backgroundColor = BG_COLOR;
    CGRect itemFrame = CGRectMake(0, 0, self.bounds.size.width, 44);
    if (self.title) {
        itemFrame.size.height = 30;
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:itemFrame];
        titleLabel.backgroundColor = [UIColor whiteColor];
        titleLabel.font = SUB_TITLE_FONT;
        titleLabel.textColor = SUB_TITLE_COLOR;
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.text = self.title;
        [self.contentView addSubview:titleLabel];
        itemFrame.origin.y = itemFrame.size.height;
        itemFrame.size.height = 44;
    }
    for (NSInteger i = 0; i<self.titles.count; i++) {
        NSDictionary *item = [self.titles objectAtIndex:i];
        UIButton *itemButton = [self createItemButton:item withFrame:itemFrame];
        itemButton.tag = i;
        [itemButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.buttons addObject:itemButton];
        [self.contentView addSubview:itemButton];
        itemFrame = itemButton.frame;
        itemFrame.origin.y += itemFrame.size.height-1;
    }
    
    itemFrame.origin.y += 10;
    UIButton *cancelButton = [self createItemButton:@{@"title":self.cancelButtonTitle} withFrame:itemFrame];
    cancelButton.tag = self.titles.count;
    itemFrame = cancelButton.frame;
    itemFrame.size.height += self.safeAreaInsets.bottom+10;
    
    cancelButton.frame = itemFrame;
    [cancelButton addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
//    cancelButton.backgroundColor = [UIColor redColor];
    [self.contentView addSubview:cancelButton];
    
    CGRect contentFrame = self.contentView.bounds;
    contentFrame.size.height = itemFrame.origin.y+itemFrame.size.height;
    self.contentView.frame = contentFrame;
    [self addSubview:self.contentView];
}
- (void)show{
    CGRect contentFrame = self.contentView.bounds;
    contentFrame.origin.y = [APP_KEY_WIN screen].bounds.size.height;
    self.contentView.frame = contentFrame;
    self.backgroundView.alpha = 0;
    [APP_KEY_WIN addSubview:self];
    WEAK(weakSelf, self);
    DLOG(@"%@", NSStringFromUIEdgeInsets([APP_KEY_WIN safeAreaInsets]));
    [UIView animateWithDuration:0.2
                     animations:^{
        CGRect frame = weakSelf.contentView.bounds;
        frame.origin.y = [APP_KEY_WIN screen].bounds.size.height - frame.size.height - [APP_KEY_WIN safeAreaInsets].bottom;
//        weakSelf.contentView.frame = frame;
        weakSelf.contentView.transform = CGAffineTransformMakeTranslation(0, -weakSelf.contentView.bounds.size.height);
        self.backgroundView.alpha = 1;
    }];
}
- (void) close:(id)button{
    DLOG(@"close:%@", button);
    WEAK(weakSelf, self);
    [UIView animateWithDuration:0.2
                     animations:^{
                         CGRect frame = self.contentView.bounds;
                         frame.origin.y = [APP_KEY_WIN screen].bounds.size.height;
                         weakSelf.contentView.transform = CGAffineTransformIdentity;
                         self.backgroundView.alpha = 0;
                     }
                     completion:^(BOOL finished) {
                         [weakSelf removeFromSuperview];
                         if(button && weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(actionSheetCanceled:)]){
                             [weakSelf.delegate actionSheetCanceled:weakSelf];
                         }
                     }];
}
- (void)clickButton:(UIButton*)button{
    NSInteger i = [button tag];
    DLOG(@"clickButton:%@, tag:%ld", button, i);
    if (self.delegate && [self.delegate respondsToSelector:@selector(actionSheet:clickedButtonAtIndex:data:)]) {
        if (i>=0 && i<self.titles.count) {
            id data = [self.titles objectAtIndex:i];
            [self.delegate actionSheet:self clickedButtonAtIndex:i data:data];
        }
    }
    [self close:nil];
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/
- (void)layoutSubviews{
    [super layoutSubviews];
}
@end
